// import { useMessage } from '@/hooks'
import { bwSortableUtil } from '@/utils/drag'
import { useComDesignStoreWithOut, designUtils } from '@/store'

export function useSortable(ele: HTMLElement) {
  // const { createInfoModal } = useMessage()
  const designerStore = useComDesignStoreWithOut()

  if (ele) {
    bwSortableUtil(ele, {
      sort: true,
      animation: 100,
      draggable: '.bw-design-drag-item',
      group: { name: 'drag-group', pull: 'clone', put: true },
      receivClass: 'bw-slot-container',
      onDragEnd(dragInfo) {
        const { from, to, related, dragged, position } = dragInfo

        if (from && to && related && dragged) {
          const structs = designerStore.getStructList
          const toNodeId = to.getAttribute('nodeid')
          const slotKey = to.getAttribute('soltcode')
          const fromNodeId = from.getAttribute('nodeid')
          const rEleId = related.getAttribute('id') ?? ''
          const dEleId = dragged.getAttribute('id') ?? ''
          const rNodeId =
            related.getAttribute('nodeid') ?? rEleId.replace('com_', '')
          const dNodeId =
            dragged.getAttribute('nodeid') ?? dEleId.replace('com_', '')

          if (rNodeId && dNodeId && toNodeId && fromNodeId) {
            /** 同级元素拖拽排序 */
            if (toNodeId === fromNodeId) {
              const rNodeInfo = designUtils.findDomNodeInfo(structs, rNodeId)

              let newIndex = rNodeInfo?.index ?? 0
              if (position === 'bottom') {
                newIndex += 1
              }
              designerStore.onDragNodeEleSort({
                nodeId: dNodeId,
                pNodeId: toNodeId,
                newIndex: newIndex,
                slotKey: slotKey ?? 'default',
              })
            } else {
              const rNodeInfo = designUtils.findDomNodeInfo(structs, rNodeId)
              let newIndex = rNodeInfo?.index ?? 0
              if (position === 'bottom') {
                newIndex += 1
              }
              designerStore.onDragNodeEleSort({
                slotKey,
                nodeId: dNodeId,
                pNodeId: toNodeId,
                newIndex: newIndex,
              })
            }
          }
        }
      },
    })
  }
}
